package filter;

import entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 获取请求url
        String requestURI = request.getRequestURI();
        // 需要放行的路径
        List<String> urls = Arrays.asList("/test/login","/xxx");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null || urls.contains(requestURI)) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 未登录 跳转登录页面
            request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
